package com.cloud.goal.web;

import java.util.List;

import com.cloud.goal.model.Plan;
import com.cloud.goal.service.PlanService;
import com.cloud.platform.BaseHandler;
import com.cloud.platform.json.JSONArray;
import com.cloud.platform.json.JSONObject;
import com.cloud.platform.util.DateUtil;
import com.cloud.platform.util.StringUtil;

public class PlanBean extends BaseHandler {

	private PlanService planService;
	
	private Plan plan;
	private List<Plan> planList;
	
	/**
	 * get plans for dwr
	 * 
	 * @param goalId
	 * @return
	 */
	public String dynGetPlans(String goalId) {
		
		JSONArray plans = new JSONArray();
		JSONObject plan = null;
		
		try {
			// get goal's plans
			planList = planService.searchPlans(goalId);
			
			for(Plan p : planList) {
				plan = new JSONObject();
				plan.put("i", p.getId());
				plan.put("v", p.getName());
				
				plans.put(plan);
			}
			
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return plans.toString();
	}
	
	/**
	 * remove goal plan
	 */
	public void removePlan() {
		planService.removePlan(getParameter("planId"));
	}
	
	/**
	 * search goal plan list
	 * 
	 * @return
	 */
	public List<Plan> getPlanList() {
		if(planList == null) {
			String goalId = getParameter("goalId");
			
			planList = planService.searchPlans(goalId);
		}
		return planList;
	}
	
	/**
	 * save goal
	 */
	public void savePlan() {
		try {
			String goalId = getParameter("goalId");
			String startDate = getParameter("startDate");
			String endDate = getParameter("endDate");
			
			if(!StringUtil.isNullOrEmpty(goalId)) {
				plan.setGoalId(goalId);
			}
			
			plan.setStartDate(DateUtil.parseDate(startDate));
			plan.setEndDate(DateUtil.parseDate(endDate));
			
			planService.savePlan(plan);
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * get goal plan by plan id
	 * 
	 * @return
	 */
	public Plan getPlan() {
		if(plan == null) {
			plan = planService.getPlan(getParameter("planId"));
		}
		
		return plan;
	}

	/**
	 * =======================  getters and setters  =======================
	 */
	public void setPlan(Plan plan) {
		this.plan = plan;
	}
	
	public void setPlanList(List<Plan> planList) {
		this.planList = planList;
	}
	
	public PlanService getPlanService() {
		return planService;
	}

	public void setPlanService(PlanService planService) {
		this.planService = planService;
	}
}
